package com.yayan.xh.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.yayan.xh.bean.ImageBean;

public class ImageDao extends ConnectionBase implements IImageDao {
	
	private Connection conn = null;
	
	private QueryRunner qRunner = null;
	
	private PreparedStatement ps = null;
	
	private ResultSet rsKey = null;

	@Override
	public List<ImageBean> getImageByMatchIdBack(Map<String, String> map) throws Exception{
		List<ImageBean> result = null;
		try {
			qRunner = new QueryRunner();
			String sql = "select * from tb_image where shop_id=? and m_id=? order by im_createdatetime desc";
			conn = getConn();
			result = qRunner.query(conn, sql, new BeanListHandler<ImageBean>(ImageBean.class), map.get("shopId"), map.get("matchId"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return result;
	}

	@Override
	public boolean saveImage(Map<String, String> map) throws Exception{
		boolean f = false;
		try {
			String sql = "insert into tb_image(shop_id, im_url, m_id, im_createdatetime) values(?,?,?,now())";
			conn=getConn();
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);
			ps.setObject(1, map.get("shopId"));
			ps.setObject(2, map.get("image"));
			ps.setObject(3, map.get("matchId"));
			f = ps.executeUpdate() > 0 ? true : false;
			conn.commit();
			conn.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return f;
	}

	@Override
	public boolean delImage(Map<String, String> map) throws Exception{
		boolean f = false;
		try {
			String sql = "delete from tb_image where im_id=?";
			conn=getConn();
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);
			ps.setObject(1, map.get("id"));
			f = ps.executeUpdate() > 0 ? true : false;
			conn.commit();
			conn.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return f;
	}

	@Override
	public ImageBean getImageByIdBack(Map<String, String> map) throws Exception {
		ImageBean result = null;
		try {
			qRunner = new QueryRunner();
			String sql = "select * from tb_image where im_id=? order by im_createdatetime desc";
			conn = getConn();
			result = qRunner.query(conn, sql, new BeanHandler<ImageBean>(ImageBean.class), map.get("id"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return result;
	}

}
